package sky.treasure;

import sky.treasure.results.EndOfAlgorithm;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 10.01.14
 * Time: 23:29
 * To change this template use File | Settings | File Templates.
 */
public class SnakeCoordinator implements ICoordinator {

    private Direction mainDirection;
    private Direction auxiliaryDirection;
    private Coordinates startCoordinates;
    private Area area;

    public SnakeCoordinator(Area area, Coordinates startCoordinates) {
        this.area = area;
        this.mainDirection = Direction.RIGHT;
        this.auxiliaryDirection = Direction.DOWN;
        this.startCoordinates = startCoordinates;
    }

    public SnakeCoordinator(Area area, Direction mainDirection, Direction auxiliaryDirection, Coordinates startCoordinates) {
        this.area = area;
        this.mainDirection = mainDirection;
        this.auxiliaryDirection = auxiliaryDirection;
        this.startCoordinates = startCoordinates;
    }

    @Override
    public Cell getNextCell(Coordinates coordinates) {
        Coordinates temp = new Coordinates(coordinates);                       //refactor
        mainDirection.changeCoordinate(temp);                                  //
        Cell cell = area.getCell(temp);                                        //
        if (cell.isAbroad()) {
            temp = new Coordinates(coordinates);                               //
            auxiliaryDirection.changeCoordinate(temp);                         //
            cell = area.getCell(temp);
            if (cell.isAbroad()) {
                cell = new Cell(cell.getCoordinates());
                cell.addProperty(new EndOfAlgorithm());                                                                //
            }
            mainDirection = mainDirection.opposite();
        }
        return cell;
    }

    public Cell getFirstCell() {
        return area.getCell(startCoordinates);
    }

    @Override
    public Area getArea() {
        return area;
    }
}
